/*******************************************************************************
 * Copyright (c) 2008-2009 zhang yuexiang.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package org.xfeep.alaya.jta;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

import org.xfeep.asura.core.ComponentType;
import org.xfeep.asura.core.CoreConsts;
import org.xfeep.asura.core.annotation.Config;
import org.xfeep.asura.core.annotation.Property;
import org.xfeep.asura.core.annotation.Ref;
import org.xfeep.asura.core.annotation.Service;

@Service(type=ComponentType.ON_DEMAND)
@Config("")
public class SmartConnection implements Connection, JtaTransactionListener {

	Map<Transaction, Connection> transactionToConnectionMap = new ConcurrentHashMap<Transaction, Connection>();
	
	@Property
	String dataSourceConfigId;
	
	@Ref(matcher="_cid=$.dataSourceConfigId"+CoreConsts.ON_DEMAND_SEPRATOR)
	DataSource dataSource;
	
	@Ref
	TransactionManager transactionManager;
	
	public Connection getConnection() throws SQLException {

		Transaction tx = null;
		try {
			tx = transactionManager.getTransaction();
		} catch (SystemException e) {
			throw new IllegalStateException("Cannot get current transaction", e);
		}
		if (tx == null){
			throw new IllegalStateException("SmartConnection Service must be used in a container-managed transaction service");
		}

		Connection connection  = transactionToConnectionMap.get(tx);
		if (connection == null){
			transactionToConnectionMap.put(tx, connection = dataSource.getConnection());
			try {
			TransactionLifeCycleMonitorService.addSynchronization(tx, this);
			} catch (Exception e) {
				throw new IllegalStateException("can not register and join transaction", e);
			}
		}
		return connection;
	}

	public void clearWarnings() throws SQLException {
		getConnection().clearWarnings();
	}

	public void close() throws SQLException {
		getConnection().close();
	}

	public void commit() throws SQLException {
		getConnection().commit();
	}

	public Array createArrayOf(String typeName, Object[] elements)
			throws SQLException {
		return getConnection().createArrayOf(typeName, elements);
	}

	public Blob createBlob() throws SQLException {
		return getConnection().createBlob();
	}

	public Clob createClob() throws SQLException {
		return getConnection().createClob();
	}

	public NClob createNClob() throws SQLException {
		return getConnection().createNClob();
	}

	public SQLXML createSQLXML() throws SQLException {
		return getConnection().createSQLXML();
	}

	public Statement createStatement() throws SQLException {
		return getConnection().createStatement();
	}

	public Statement createStatement(int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return getConnection().createStatement(resultSetType, resultSetConcurrency,
				resultSetHoldability);
	}

	public Statement createStatement(int resultSetType, int resultSetConcurrency)
			throws SQLException {
		return getConnection().createStatement(resultSetType, resultSetConcurrency);
	}

	public Struct createStruct(String typeName, Object[] attributes)
			throws SQLException {
		return getConnection().createStruct(typeName, attributes);
	}

	public boolean getAutoCommit() throws SQLException {
		return getConnection().getAutoCommit();
	}

	public String getCatalog() throws SQLException {
		return getConnection().getCatalog();
	}

	public Properties getClientInfo() throws SQLException {
		return getConnection().getClientInfo();
	}

	public String getClientInfo(String name) throws SQLException {
		return getConnection().getClientInfo(name);
	}

	public int getHoldability() throws SQLException {
		return getConnection().getHoldability();
	}

	public DatabaseMetaData getMetaData() throws SQLException {
		return getConnection().getMetaData();
	}

	public int getTransactionIsolation() throws SQLException {
		return getConnection().getTransactionIsolation();
	}

	public Map<String, Class<?>> getTypeMap() throws SQLException {
		return getConnection().getTypeMap();
	}

	public SQLWarning getWarnings() throws SQLException {
		return getConnection().getWarnings();
	}

	public boolean isClosed() throws SQLException {
		return getConnection().isClosed();
	}

	public boolean isReadOnly() throws SQLException {
		return getConnection().isReadOnly();
	}

	public boolean isValid(int timeout) throws SQLException {
		return getConnection().isValid(timeout);
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return getConnection().isWrapperFor(iface);
	}

	public String nativeSQL(String sql) throws SQLException {
		return getConnection().nativeSQL(sql);
	}

	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return getConnection().prepareCall(sql, resultSetType, resultSetConcurrency,
				resultSetHoldability);
	}

	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return getConnection().prepareCall(sql, resultSetType, resultSetConcurrency);
	}

	public CallableStatement prepareCall(String sql) throws SQLException {
		return getConnection().prepareCall(sql);
	}

	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
			throws SQLException {
		return getConnection().prepareStatement(sql, resultSetType, resultSetConcurrency,
				resultSetHoldability);
	}

	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return getConnection().prepareStatement(sql, resultSetType, resultSetConcurrency);
	}

	public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
			throws SQLException {
		return getConnection().prepareStatement(sql, autoGeneratedKeys);
	}

	public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
			throws SQLException {
		return getConnection().prepareStatement(sql, columnIndexes);
	}

	public PreparedStatement prepareStatement(String sql, String[] columnNames)
			throws SQLException {
		return getConnection().prepareStatement(sql, columnNames);
	}

	public PreparedStatement prepareStatement(String sql) throws SQLException {
		return getConnection().prepareStatement(sql);
	}

	public void releaseSavepoint(Savepoint savepoint) throws SQLException {
		getConnection().releaseSavepoint(savepoint);
	}

	public void rollback() throws SQLException {
		getConnection().rollback();
	}

	public void rollback(Savepoint savepoint) throws SQLException {
		getConnection().rollback(savepoint);
	}

	public void setAutoCommit(boolean autoCommit) throws SQLException {
		getConnection().setAutoCommit(autoCommit);
	}

	public void setCatalog(String catalog) throws SQLException {
		getConnection().setCatalog(catalog);
	}

	@SuppressWarnings("unchecked")
	public void setClientInfo(Properties properties)
			throws SQLClientInfoException {
		try {
			getConnection().setClientInfo(properties);
		} catch (SQLException e) {
			throw new SQLClientInfoException(Collections.EMPTY_MAP, e);
		}
	}

	@SuppressWarnings("unchecked")
	public void setClientInfo(String name, String value)
			throws SQLClientInfoException {
		try {
			getConnection().setClientInfo(name, value);
		} catch (SQLException e) {
			throw new SQLClientInfoException(Collections.EMPTY_MAP, e);
		}
	}

	public void setHoldability(int holdability) throws SQLException {
		getConnection().setHoldability(holdability);
	}

	public void setReadOnly(boolean readOnly) throws SQLException {
		getConnection().setReadOnly(readOnly);
	}

	public Savepoint setSavepoint() throws SQLException {
		return getConnection().setSavepoint();
	}

	public Savepoint setSavepoint(String name) throws SQLException {
		return getConnection().setSavepoint(name);
	}

	public void setTransactionIsolation(int level) throws SQLException {
		getConnection().setTransactionIsolation(level);
	}

	public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
		getConnection().setTypeMap(map);
	}

	public <T> T unwrap(Class<T> iface) throws SQLException {
		return getConnection().unwrap(iface);
	}


	public void afterCompletion(Transaction tx, int arg0) {
//		new Exception("afterCompletion").printStackTrace(System.out);
	}

	public void beforeCompletion(Transaction tx) {
//		new Exception("beforeCompletion").printStackTrace(System.out);
		try {
//			Transaction tx = transactionManager.getTransaction();
			TransactionLifeCycleMonitorService.removeSynchronization(tx, this);
			Connection connection = transactionToConnectionMap.remove(tx);
			connection.close();
//		} catch (SystemException e) {
//			throw new IllegalStateException("can not access Transaction", e);
		} catch (SQLException e) {
			throw new IllegalStateException("can not close Connection", e);
		}
	
	};

	
}
